package com.macaline.util;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ParamsUtil {

    private static Pattern linePattern = Pattern.compile("_(\\w)");
    private static Pattern humpPattern = Pattern.compile("[A-Z]");


    /**
     * json转Map，key值进行驼峰转行
     * @param data json信息
     * @return
     * @throws ParseException
     */
    public static Map jsonToMap(JSONObject data) throws ParseException {
        return jsonToMap(data, null, null, null);
    }
    /**
     * json转Map，key值进行驼峰转行
     * @param data json信息
     * @return
     * @throws ParseException
     */
    public static Map jsonToMap(JSONObject data, Map<String, String> keyRepMap) throws ParseException {
        return jsonToMap(data, null, null, keyRepMap);
    }

    /**
     * json转Map，key值进行驼峰转行
     * @param data json信息
     * @param keyDelString key在驼峰转换时要去出的字段
     * @return
     * @throws ParseException
     */
    public static Map jsonToMap(JSONObject data, String keyDelString) throws ParseException {
        return jsonToMap(data, null, keyDelString, null);
    }

    /**
     * json转Map，key值进行驼峰转行
     * @param data json信息
     * @param keyStart key值前缀名称
     * @param keyRepMap 需要替换的key值，以转换后的key进行比较
     * @return
     * @throws ParseException
     */
    public static Map jsonToMap(JSONObject data, String keyStart, String keyDelString, Map<String, String> keyRepMap) throws ParseException {
        // 如果key前缀为空，那么设置为空字符
        if(keyStart == null){
            keyStart = "";
        }
        HashMap<Object, Object> result = new HashMap<>();
        Set<String> keySet = data.keySet();
        for(String key : keySet){
            // 如果是json类型那么进行遍历
            Object o = data.get(key);
            if(o instanceof JSONObject){
                JSONObject item = (JSONObject) o;
                result.putAll(jsonToMap(item, keyStart, keyDelString, keyRepMap));
                continue;
            }
            if(o instanceof JSONArray){
                JSONArray array = (JSONArray) o;
                JSONObject item = array.getJSONObject(0);
                result.putAll(jsonToMap(item, keyStart, keyDelString, keyRepMap));
                continue;
            }
            // 如果是时间的话那么进行转格式
            if(ParamsUtil.isDateKey(key)){
                result.put(ParamsUtil.humpToLine(key), ParamsUtil.formatISO8601(data.getString(key)));
                continue;
            }
            String value = data.getString(key);
            if(keyDelString != null && key.indexOf(keyDelString) > -1){
                key = key.replaceAll(keyDelString, "");
            }
            if(keyRepMap != null){
                if(keyRepMap.containsKey(key)){
                    result.put(keyStart + keyRepMap.get(key), value);
                    continue;
                }
            }
            result.put(keyStart + ParamsUtil.humpToLine(key), value);

        }
        return result;
    }



    public static Boolean isDateKey(String key){
        if(key.indexOf("Time") > -1){
            return true;
        }
        return false;
    }

    public static Date formatISO8601(String dateStr) throws ParseException {
        LinkedList<String> formatList = new LinkedList<String>();
        formatList.add("yyyy-MM-dd'T'HH:mm:ss.SSS+hh:ss");
        formatList.add("yyyy-MM-dd'T'HH:mm:ss+hh:ss");
        for(String format : formatList){
            try {
                DateFormat sdf1 = new SimpleDateFormat(format);
                Date dt =  sdf1.parse(dateStr.replaceAll(" ", ""));
                return dt;
            }catch (Exception e){
                continue;
            }
        }

        return null;
    }

    /**
     * 下划线转驼峰
     * @param str 数据
     * @return
     */
    public static String lineToHump(String str) {
        str = str.toLowerCase();
        Matcher matcher = linePattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }


    /**
     * 驼峰转下划线
     * @param str 数据
     * @return
     */
    public static String humpToLine(String str) {
        Matcher matcher = humpPattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        if(sb.toString().startsWith("_")){
            return sb.toString().substring(1);
        }
        return sb.toString();
    }


    public static void main(String[] args) {

    }
}
